<script setup>
import { ref, computed } from 'vue'
import { addEmployeeService, updateEmployeeService } from '@/api/employee.js'
import { updateUserPasswordService } from '@/api/user.js'
import { fileUploadService } from '@/api/common.js'
import { Lock, Plus } from '@element-plus/icons-vue'
import { imageUrlToFile } from '@/utils/request'

// 控制抽屉的显示与隐藏
const visibleDrawer = ref(false)

// 控制对话框的显示与隐藏
const visibleDialog = ref(false)

const defaultDTO = {
  username: null, // 用户名
  name: null, // 姓名
  gender: null, // 性别
  age: null, // 年龄
  mobilePhone: null, // 移动电话
  idNumber: null, // 身份证号码
  email: null, // 电子邮箱
  address: null, // 地址
  avatarUrl: null, // 头像链接
  position: null, // 职位
  salary: null, // 每月薪资
  skills: null // 员工技能
}

const employeeDTO = ref({ ...defaultDTO })

const passwordDTO = ref({
  id: null,
  password: null,
  rePassword: null
})

// 薪资转换
const salaryConverter = computed({
  get() {
    if (employeeDTO.value.salary) {
      return employeeDTO.value.salary / 100
    } else {
      return null
    }
  },
  set(value) {
    employeeDTO.value.salary = value * 100
  }
})

// 表单校验规则
const rules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\w{4,32}$/,
      message: '密码必须是4~32位的字母、数字、下划线',
      trigger: 'blur'
    }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\w{4,32}$/,
      message: '密码必须是4~32位的字母、数字、下划线',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordDTO.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 向外暴露方法
const open = (row) => {
  visibleDrawer.value = true // 打开抽屉
  if (row.id) {
    employeeDTO.value = {
      id: row.id,
      username: row.username,
      name: row.name,
      gender: row.gender,
      age: row.age,
      mobilePhone: row.mobilePhone,
      idNumber: row.idNumber,
      email: row.email,
      address: row.address,
      avatarUrl: row.avatarUrl,
      position: row.position,
      salary: row.salary,
      skills: row.skills
    }
    passwordDTO.value = { id: row.userId }
  } else {
    employeeDTO.value = { ...defaultDTO }
  }
  imgInfo.value.name = ''
  imgInfo.value.url = ''
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (imgInfo.value.name) {
    // 将网络图片地址转换为file对象
    const file = await imageUrlToFile(imgInfo.value.url, imgInfo.value.name)
    const res = await fileUploadService(file)
    employeeDTO.value.avatarUrl = res.data.data
  }
  if (employeeDTO.value.id) {
    await updateEmployeeService(employeeDTO.value)
    ElNotification({
      title: '修改成功',
      type: 'success'
    })
  } else {
    await addEmployeeService(employeeDTO.value)
    ElNotification({
      title: '新增成功',
      type: 'success'
    })
  }
  visibleDrawer.value = false
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDrawer.value = false
  employeeDTO.value = { ...defaultDTO }
}

// 修改密码
const formRef = ref()
const handleUpdatePassword = async () => {
  await formRef.value.validate()
  await updateUserPasswordService(passwordDTO.value.rePassword, passwordDTO.value.id)
  ElNotification({
    title: '用户密码修改成功',
    type: 'success'
  })
  visibleDialog.value = false
  passwordDTO.value.password = null
  passwordDTO.value.rePassword = null
}

// 取消修改密码
const handleCancelUpdatePassword = () => {
  visibleDialog.value = false
  passwordDTO.value.password = null
  passwordDTO.value.rePassword = null
}

// 头像上传
const imgInfo = ref({
  name: '', // 文件名
  url: '' // 网络图片地址
})
const getImageUrl = (uploadFile) => {
  imgInfo.value.name = uploadFile.name
  imgInfo.value.url = URL.createObjectURL(uploadFile.raw) // 预览图片
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer v-model="visibleDrawer" :title="employeeDTO.id ? '修改员工信息' : '新增员工'">
    <el-form :model="employeeDTO" ref="formRef" label-width="auto">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="employeeDTO.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatarUrl">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="getImageUrl"
        >
          <img
            v-if="employeeDTO.avatarUrl || imgInfo.url"
            :src="imgInfo.url ? imgInfo.url : employeeDTO.avatarUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="employeeDTO.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="employeeDTO.gender">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number
          v-model="employeeDTO.age"
          placeholder="请输入年龄"
          :min="0"
          :max="127"
          style="width: 180px"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="移动电话" prop="mobilePhone">
        <el-input v-model="employeeDTO.mobilePhone" placeholder="请输入移动电话"></el-input>
      </el-form-item>
      <el-form-item label="身份证号码" prop="idNumber">
        <el-input v-model="employeeDTO.idNumber" placeholder="请输入身份证号码"></el-input>
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="employeeDTO.email" placeholder="请输入电子邮箱"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="employeeDTO.address" placeholder="请输入地址"></el-input>
      </el-form-item>
      <el-form-item label="职位" prop="position">
        <el-select v-model="employeeDTO.position">
          <el-option label="店长" value="店长"></el-option>
          <el-option label="收银员" value="收银员"></el-option>
          <el-option label="采购员" value="采购员"></el-option>
          <el-option label="服务员" value="服务员"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="每月薪资" prop="salary">
        <el-input v-model="salaryConverter" placeholder="请输入薪资(元/月)"></el-input>
      </el-form-item>
      <el-form-item label="员工技能" prop="skills">
        <el-input v-model="employeeDTO.skills" placeholder="请输入员工技能"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="handleSubmit">提交</el-button>
        <el-button type="info" plain @click="handleCancel">取消</el-button>
        <el-button v-if="employeeDTO.id" type="danger" plain @click="visibleDialog = true"
          >修改密码</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 修改密码对话框 -->
    <el-dialog v-model="visibleDialog" title="修改密码" width="500">
      <el-form :model="passwordDTO" :rules="rules" ref="formRef" label-width="auto">
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="passwordDTO.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="rePassword">
          <el-input
            v-model="passwordDTO.rePassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelUpdatePassword">取消</el-button>
          <el-button type="primary" @click="handleUpdatePassword">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
    }
  }
}
</style>
